#!/usr/bin/python
#-*- coding: iso-8859-15 -*-

from cat import ngcCatalogue,crossCatalogue
import struct
import numpy as np

class aliceCatalogue():

	crossCat=crossCatalogue()
	ngcCat=ngcCatalogue()

	tileSizes=[4,9,18]
	Names=['NGC','MESSIER','NAMED_STARS','OBJECTS_IN_TILE','DSS2atlas','atlas']
	fileNames=[]

	master_format='24sIIIII'
	MM=struct.Struct(master_format)

	ngc_format='HHfffH24s4sH'
	s=struct.Struct(ngc_format)

	stars_format='IfffH5s3s18s'
	SS=struct.Struct(stars_format)

	obj_format='HHHHHHH'
	obj=struct.Struct(obj_format)


	n_messier=0
	n_stars=0
	messier_list=[]

	def __init__(self):
		for s in self.tileSizes:
			for n in self.Names:
				self.fileNames.append(n+str(s))


	def tileLimits(self,N,Gsize):
		raN=N % (360/Gsize)
   		decN=(int)(N / (360/Gsize))
		ra=raN*Gsize+Gsize/2
   		dec=-90+decN*Gsize+Gsize/2
		ra0=ra-Gsize/2
		dec0=dec-Gsize/2
		ra1=ra+Gsize/2
		dec1=dec+Gsize/2
		return ra0,dec0,ra1,dec1

	def OBJinTile(self,N,Cat,Gsize):
		ra0,dec0,ra1,dec1=map(lambda x:x*np.pi/180, self.tileLimits(N,Gsize))
		print ra0,dec0,ra1,dec1
		if (Cat=='NGC'):
			return self.ngcCat.filter(ra0,dec0,ra1,dec1)
		if (Cat=='STARS'):
			return self.crossCat.filter(ra0,dec0,ra1,dec1)

	def nTile(self,Gsize):
		return (180/Gsize)*(360/Gsize)

	def writeIXD(self,Cat,Gsize):
		filename=Cat+str(Gsize)+'.ixd'
		f=open(filename,'w')
		for n in nTile:	
			for o in OBJinTile(n,Cat,Gsize):
				if (Cat=='NGC' or Cat=='MESSIER'):
					line= s.pack(NG,Iflag,o['_RA'],o['_DEC'],o['size'],n_ngc,DESC,o['Type'],n)
				else:
					line= SS.pack(NG,Iflag,o['_RA'],o['_DEC'],o[5],n_ngc,DESC,o[1],n)
				f.write(line)
		f.close()

	def writeMasterIXD(self):
		pass


if __name__=='__main__':
	a=aliceCatalogue()
	Gsize=14
	#print a.crossCat.objs	
	for i in range(a.nTile(Gsize)):
		print "TILE:",i
		for o in a.OBJinTile(i,'STARS',Gsize):
			if (o['aux_Name']!='0.0'):
				print o['_ID'],o['_RA'],o['_DEC'],o['aux_Name']
		





